//
//  BKPhone_MainView.m
//  bestkeep
//
//  Created by yons on 16/11/30.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKPhone_MainView.h"
#import "BKPhoneCollectionCell.h"

@interface BKPhone_MainView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property (nonatomic, strong) UIView *tariffeView;
@property (nonatomic, strong) UIView *flowView;
@property (nonatomic, strong) UILabel *explainLabel;
@property (nonatomic, strong) UILabel *tempInfoLabel;

@end

@implementation BKPhone_MainView

{    //用于在增加用户体验时，防止多次请求；
    BOOL isFirstRunTariffe;
    BOOL isFirstRunFlow;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        [self initViews];
       
        [self.myScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_top).offset(43+1);
            make.left.mas_equalTo(self.mas_left);
            make.right.mas_equalTo(self.mas_right);
            make.bottom.mas_equalTo(self.mas_bottom);
        }];
        [self.tariffeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.myScrollView.mas_top);
            make.bottom.mas_equalTo(self.mas_bottom);
            make.left.mas_equalTo(self.myScrollView.mas_left);
            make.width.mas_equalTo(ScreenWidth);
        }];
        [self.flowView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.myScrollView.mas_top);
            make.bottom.mas_equalTo(self.mas_bottom);
            make.right.mas_equalTo(self.myScrollView.mas_right);
            make.width.mas_equalTo(ScreenWidth);
            make.left.mas_equalTo(self.tariffeView.mas_right);
        }];
        [self.flowCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.flowView.mas_left);
            make.top.mas_equalTo(self.flowView.mas_top);
            make.right.mas_equalTo(self.flowView.mas_right);
            make.bottom.mas_equalTo(self.flowView.mas_bottom);
        }];
        [self.tariffeCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.tariffeView.mas_left);
            make.top.mas_equalTo(self.tariffeView.mas_top);
            make.right.mas_equalTo(self.tariffeView.mas_right);
            make.bottom.mas_equalTo(self.tariffeView.mas_bottom);
        }];
    }
    return self;
}

-(void)initViews{
    
    _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_leftButton setTitle:@"充话费" forState:UIControlStateNormal];
    [_leftButton.titleLabel setFont:[Common systemFontOfSize:14]];
    [_leftButton setTitleColor:kSelectColor forState:UIControlStateNormal];
    [_leftButton addTarget:self action:@selector(buttonallAction:) forControlEvents:UIControlEventTouchUpInside];
    _leftButton.tag = 6666;
    [self addSubview:_leftButton];
    [_leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left);
        make.width.mas_equalTo(ScreenWidth/2);
        make.top.mas_equalTo(self.mas_top).offset(7.5f);
        make.height.mas_offset(@(43-2-7.5f));
    }];
    
    _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightButton setTitle:@"充流量" forState:UIControlStateNormal];
    [_rightButton setTitleColor:kUnselectColor forState:UIControlStateNormal];
    [_rightButton.titleLabel setFont:[Common systemFontOfSize:14]];
    [_rightButton addTarget:self action:@selector(buttonallAction:) forControlEvents:UIControlEventTouchUpInside];
    _rightButton.tag = 8888;
    [self addSubview:_rightButton];
    [_rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.mas_right);
        make.left.mas_equalTo(self.leftButton.mas_right);
        make.top.mas_equalTo(self.mas_top).offset(7.5f);
        make.height.mas_equalTo(self.leftButton.mas_height);
    }];
    
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = RGBACOLOR(242, 242, 242, 1);
    [self addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left);
        make.right.mas_equalTo(self.mas_right);
        make.height.mas_offset(@0.5);
        make.top.mas_equalTo(self.mas_top).offset(41);
    }];
    
    _markLabel = [[UIView alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth/2.f, 2)];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)RGB(111, 229, 237).CGColor,
                             (__bridge id)RGB(79, 239, 179).CGColor];
    // 起始点
    gradientLayer.startPoint = CGPointMake(0, 0);
    
    // 结束点
    gradientLayer.endPoint   = CGPointMake(1, 0);
    gradientLayer.cornerRadius = 1.0f;
    gradientLayer.masksToBounds = YES;
    gradientLayer.frame = _markLabel.bounds;
    
    [self addSubview:_markLabel];
    [_markLabel.layer addSublayer:gradientLayer];
}

- (void)buttonallAction:(UIButton *)sender{
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = _markLabel.frame;
        if (sender.tag ==8888) {
            frame.origin.x = ScreenWidth/2;
            [self.leftButton setTitleColor:kUnselectColor forState:UIControlStateNormal];
            [self.rightButton setTitleColor:kSelectColor forState:UIControlStateNormal];
            self.myScrollView.contentOffset = CGPointMake(ScreenWidth, 0);
            
        }else if (sender.tag == 6666){
            frame.origin.x = 0;
            [self.leftButton setTitleColor:kSelectColor forState:UIControlStateNormal];
            [self.rightButton setTitleColor:kUnselectColor forState:UIControlStateNormal];
            self.myScrollView.contentOffset = CGPointMake(0, 0);
        }
        self.markLabel.frame = frame;
    }];
}

#pragma mark ---CollectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.tariffeCollectionView) {
        NSLog(@"%@",self.phoneCardsTariffeList.shelfInfos);
        if (self.phoneCardsTariffeList.shelfInfos.count > 0) {
            [self.tariffeArray removeAllObjects];
            self.tariffeArray = [NSMutableArray arrayWithArray:self.phoneCardsTariffeList.shelfInfos];
        }
        return self.tariffeArray.count;
    }
    if (collectionView == self.flowCollectionView) {
        if (self.phoneCardsFlowList.shelfInfos.count > 0) {
            [self.flowArray removeAllObjects];
            self.flowArray = [NSMutableArray arrayWithArray:self.phoneCardsFlowList.shelfInfos];
        }
        return self.flowArray.count;
    }
    return 6;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.flowCollectionView) {
        if (self.flowArray.count < indexPath.row) {
            return nil;
        }
        ShelfInfos *shelfInfos = self.flowArray[indexPath.row];
        BKPhoneCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"flow" forIndexPath:indexPath];
        cell.bigTitleLabel.text = [NSString stringWithFormat:@"%@",shelfInfos.facePrice];
        if (shelfInfos.salePrice) {
            cell.smallTitleLabel.hidden = NO;
            cell.smallTitleLabel.text = [NSString stringWithFormat:@"售价:%@元",shelfInfos.salePrice];
        }else {
            cell.smallTitleLabel.hidden = YES;
        }
        
        if ([shelfInfos.isHasPreferential isEqualToString:@"1"]) {
            cell.preferentialImageView.hidden = NO;
        }else {
            cell.preferentialImageView.hidden = YES;
        }
        
        CALayer *layer = [cell layer];
        if (self.isSuccessFlow) {
            cell.smallTitleLabel.textColor = kSelectColor;
            cell.bigTitleLabel.textColor = kSelectColor;
            layer.borderColor = kSelectColor.CGColor;
            
        }else {
            cell.bigTitleLabel.textColor = kUnselectColor;
            cell.smallTitleLabel.textColor = kUnselectColor;
            layer.borderColor = kUnselectColor.CGColor;
            cell.preferentialImageView.hidden = YES;
        }
        layer.borderWidth = 0.5f;
        layer.cornerRadius = 3;
        layer.masksToBounds = YES;
        return cell;
    }
    if (collectionView == self.tariffeCollectionView) {
        if (self.tariffeArray.count < indexPath.row) {
            return nil;
        }
        ShelfInfos *shelfInfos = self.tariffeArray[indexPath.row];
        BKPhoneCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tariffe" forIndexPath:indexPath];
        cell.bigTitleLabel.text = [NSString stringWithFormat:@"%@",shelfInfos.facePrice];
        if (shelfInfos.salePrice) {
            cell.smallTitleLabel.hidden = NO;
            cell.smallTitleLabel.text = [NSString stringWithFormat:@"售价:%@元",shelfInfos.salePrice];
        }else {
            cell.smallTitleLabel.hidden = YES;
        }
        
        if ([shelfInfos.isHasPreferential isEqualToString:@"1"]) {
            cell.preferentialImageView.hidden = NO;
        }else {
            cell.preferentialImageView.hidden = YES;
        }
        CALayer *layer = [cell layer];
       if (self.isSuccessTariffe) {
            cell.smallTitleLabel.textColor = kSelectColor;
            cell.bigTitleLabel.textColor = kSelectColor;
            layer.borderColor = kSelectColor.CGColor;
        }else {
            cell.bigTitleLabel.textColor = kUnselectColor;
            cell.smallTitleLabel.textColor = kUnselectColor;
            layer.borderColor = kUnselectColor.CGColor;
            cell.preferentialImageView.hidden = YES;
        }
        layer.borderWidth = 0.5f;
        layer.cornerRadius = 3;
        layer.masksToBounds = YES;
        return cell;
    }
    return nil;
}

#pragma mark --- UICollectionViewDelegateFlowLayout

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((ScreenWidth-55)/3, (ScreenWidth-55)/3*140/215);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(16, 16, 10, 16);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.f;
}

-(void)chageMarkLabelColorWithContentOffset:(CGPoint)contentOffset{
    self.markLabel.transform = CGAffineTransformMakeTranslation(contentOffset.x/2, 0);
    if (contentOffset.x > ScreenWidth/2) {
        
        [self.rightButton setTitleColor:kSelectColor forState:UIControlStateNormal];
        [self.leftButton setTitleColor:kUnselectColor forState:UIControlStateNormal];
    }else if (contentOffset.x <= ScreenWidth/2) {
        
        [self.leftButton setTitleColor:kSelectColor forState:UIControlStateNormal];
        [self.rightButton setTitleColor:kUnselectColor forState:UIControlStateNormal];
   }
}

// 和UITableView类似，UICollectionView也可设置段头段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    
    if([kind isEqualToString:UICollectionElementKindSectionFooter] && collectionView == self.flowCollectionView) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"flowFooterView" forIndexPath:indexPath];
        if(footerView == nil)
        {
            footerView = [[UICollectionReusableView alloc] init];
            //临时紧急处理
        }
        [_tempInfoLabel removeFromSuperview];
        _tempInfoLabel = nil;
        _tempInfoLabel = [[UILabel alloc] init];
        [footerView addSubview:_tempInfoLabel];
        _tempInfoLabel.frame = CGRectMake(16, 1, ScreenWidth-32, 12);
        _tempInfoLabel.font = UIFontSmall;
        _tempInfoLabel.textColor = RGBACOLOR(136, 136, 136, 1);
        _tempInfoLabel.text = @"全国使用，当月有效，即时生效，支持2G/3G/4G";
        
        return footerView;
    }
    
    if([kind isEqualToString:UICollectionElementKindSectionFooter] && collectionView == self.tariffeCollectionView)
    {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"tariffeFooterView" forIndexPath:indexPath];
        if(footerView == nil)
        {
            footerView = [[UICollectionReusableView alloc] init];
        }
        return nil;
    }
    
    
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (collectionView == self.tariffeCollectionView) {
        return CGSizeZero;
    }
    return (CGSize){ScreenWidth,13};
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.tariffeCollectionView && !self.isSuccessTariffe) {
        return;
    }
    if (collectionView == self.flowCollectionView && !self.isSuccessFlow) {
        return;
    }
   
    if ([self.delegate respondsToSelector:@selector(collectionView:transInfoWithIndexPath:)]) {
        
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        cell.backgroundColor = HexColor(0xB6E8E0);
        [self.delegate collectionView:collectionView transInfoWithIndexPath:indexPath];
    }
}

#pragma mark ------ScrollView代理方法--------

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
     __weak typeof (self)wself = self;
    if (scrollView == self.myScrollView) {
        [self chageMarkLabelColorWithContentOffset:self.myScrollView.contentOffset];
        if (scrollView.contentOffset.x == 0.0f) {
            isFirstRunFlow = NO;
        }else if (scrollView.contentOffset.x == ScreenWidth) {
            isFirstRunTariffe = NO;
        }
        if (scrollView.contentOffset.x > ScreenWidth/8.f && !isFirstRunFlow) {
            if ([wself.delegate respondsToSelector:@selector(dataWithSelectPage:)]) {
                isFirstRunFlow = YES;
                [wself.delegate dataWithSelectPage:2];
            }
        }else if (scrollView.contentOffset.x < ScreenWidth/8.f*7.f && !isFirstRunTariffe) {
            if ([wself.delegate respondsToSelector:@selector(dataWithSelectPage:)]) {
                isFirstRunTariffe = YES;
                [wself.delegate dataWithSelectPage:1];
            }
        }
    }
}
#pragma mark----各种懒加载


-(UIScrollView *)myScrollView{
    if (!_myScrollView) {
        _myScrollView = [[UIScrollView alloc]init];
        _myScrollView.backgroundColor = [UIColor whiteColor];
        _myScrollView.contentSize = CGSizeMake(ScreenWidth*2, self.frame.size.height-43);
        _myScrollView.contentOffset = CGPointMake(0, 0);
        _myScrollView.userInteractionEnabled = YES;
        _myScrollView.pagingEnabled = YES;
        _myScrollView.bounces = NO;
        _myScrollView.showsVerticalScrollIndicator = NO;
        _myScrollView.showsHorizontalScrollIndicator = NO;
        _myScrollView.delegate = self;
        [self addSubview:_myScrollView];
    }
    
    return _myScrollView;
}

- (UIView *)tariffeView {
    
    if (!_tariffeView) {
        _tariffeView = [[UIView alloc] init];
        [self.myScrollView addSubview:_tariffeView];
    }
    return _tariffeView;
}
- (UIView *)flowView {
    
    if (!_flowView) {
        _flowView = [[UIView alloc] init];
        [self.myScrollView addSubview:_flowView];
    }
    return _flowView;
}
- (UILabel *)explainLabel {
    
    if (!_explainLabel) {
        _explainLabel = [[UILabel alloc] init];
        [self.flowView addSubview:_explainLabel];
    }
    return _explainLabel;
}
-(NSMutableArray *)flowArray{
    if (!_flowArray) {
        _flowArray = [[NSMutableArray alloc]init];
    }
    return _flowArray;
}

-(NSMutableArray *)tariffeArray{
    if (!_tariffeArray) {
        _tariffeArray = [[NSMutableArray alloc]init];
    }
    return _tariffeArray;
}
- (UICollectionView *)flowCollectionView {
    
    if (!_flowCollectionView) {
        //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowCollectionView = [[UICollectionView alloc] initWithFrame:self.flowView.bounds collectionViewLayout:layout];
        
        [_flowCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"flowFooterView"];
        //注册item类型 这里使用系统的类型
        [_flowCollectionView registerClass:[BKPhoneCollectionCell class] forCellWithReuseIdentifier:@"flow"];
        _flowCollectionView.backgroundColor = [UIColor whiteColor];
        _flowCollectionView.delegate = self;
        _flowCollectionView.dataSource = self;
        _flowCollectionView.tag = 1888;
        [self.flowView addSubview:_flowCollectionView];
    }
    return _flowCollectionView;
}
- (UICollectionView *)tariffeCollectionView {
    
    if (!_tariffeCollectionView) {
        //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _tariffeCollectionView = [[UICollectionView alloc] initWithFrame:self.tariffeView.bounds collectionViewLayout:layout];
        [_tariffeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"tariffeFooterView"];
        //注册item类型 这里使用系统的类型
        [_tariffeCollectionView registerClass:[BKPhoneCollectionCell class] forCellWithReuseIdentifier:@"tariffe"];
        _tariffeCollectionView.delegate = self;
        _tariffeCollectionView.dataSource = self;
        _tariffeCollectionView.backgroundColor = [UIColor whiteColor];
        _tariffeCollectionView.tag = 1889;
        [self.tariffeView addSubview:_tariffeCollectionView];
    }
    return _tariffeCollectionView;
}

@end
